<?php
namespace app\store\controller;
use app\store\model\Wxapp as WxappModel;
use app\store\model\Config as ConfigModel;
use app\store\model\UploadFile as UploadFileModel;
use app\store\model\WxappReg as WxappRegModel;
use think\Cache;

/**
 * 小程序管理
 */
class Wxapp extends Controller
{
	/**
     * 小程序设置
     */
    public function setting()
    {
        $wxapp = WxappModel::detail();
		$auth = WxappRegModel::detail();//注册信息
		$config = ConfigModel::detail();
		$wxapp['serve_domain'] = $config['api_domain'];//获取最新服务器域名列表
        if ($this->request->isAjax()) {
            $data = $this->postData('wxapp');
            if ($wxapp->edit($data)) return $this->renderSuccess('更新成功');
            return $this->renderError('更新失败');
        }
		//如果授权给第三方了，则获取
		$infor = [];
		if($wxapp['is_empower']['value']==1){
			$infor = $this->getInfor(); //服务端 - 小程序设置信息
		}
        return $this->fetch('setting', compact('wxapp','infor','auth'));
    }
	
	/**
     * 生成线上二维码
     */
	public function qrCode($wxapp_id)
	{
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$access_token;
		$data = '{"path":"/pages/index/index"}';
		$result = http_request($url,$data);
		file_put_contents('assets/qrcode/wxapp/'.$wxapp_id.'.png',$result); //获取的二维码数据存储到指定的文件
		$this->redirect('/assets/qrcode/wxapp/'.$wxapp_id.'.png');
	}
	
	/**
     * 生成体验版二维码
     */
	public function testCode($wxapp_id)
	{
		$access_token = getAccessToken();
		$path = urlencode('/pages/index/index');
		$url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token='.$access_token.'&path='.$path;
		$result = curl($url);
		file_put_contents('assets/qrcode/wxapp/'.$wxapp_id.'_test.png',$result); //获取的二维码数据存储到指定的文件
		$this->redirect('/assets/qrcode/wxapp/'.$wxapp_id.'_test.png');
	}
	
	/**
     * 设置功能介绍
     */
    public function signature()
    {
        $wxapp = WxappModel::detail();
        if ($this->request->isAjax()) {
			$app = $this->postData('wxapp');
			$access_token = getAccessToken();
			$url = 'https://api.weixin.qq.com/cgi-bin/account/modifysignature?access_token='.$access_token;
			$data = '{"signature": "'.$app['signature'].'"}';
			$result = json_decode(http_request($url,$data),true);
			if($result['errcode']!=0){
				return $this->renderError('设置失败,错误代码：'.$result['errcode'].'错误说明：'.$result['errmsg']);
			}
            if ($wxapp->edit($app)) return $this->renderSuccess('设置成功', url('wxapp/setting'));
            return $this->renderError('设置失败');
        }
        return $this->fetch('signature', compact('wxapp'));
    }

	
	/**
     * 设置服务器域名
     */
    public function servedomain()
    {
		$wxapp = WxappModel::detail();
		$config = ConfigModel::detail();
		$domain = explode(';',$config['api_domain']);
		$requestdomain = [];//request 合法域名
		$wsrequestdomain = [];//socket 合法域名
		for($n=0;$n<sizeof($domain);$n++){
			$requestdomain[$n] = 'https://'.$domain[$n];
			$wsrequestdomain[$n] = 'wss://'.$domain[$n];
		}
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token='.$access_token;
		$data = [
			'action' => 'set',
			'requestdomain' => $requestdomain,
			'wsrequestdomain' => $wsrequestdomain,
			'uploaddomain' => $requestdomain,
			'downloaddomain' => $requestdomain
		];
		$result = json_decode(http_request($url,json_encode($data)),true);
		if($result['errcode']!=0){
			return $this->error('设置失败,错误代码：'.$result['errcode'].'错误说明：'.$result['errmsg']);
		}
		$app['api_domain'] = $config['api_domain'];
		if ($wxapp->edit($app)){
          return $this->error('同步成功');
        }
		return $this->error('同步失败');
    }
	
	/**
     * 设置头像
     */
    public function sethead()
    {
        $wxapp = WxappModel::detail();
        if ($this->request->isAjax()) {
			$app = $this->postData('wxapp');
			if(empty($app['head_img'])){
				return $this->renderError('请选择一个头像图片');
			}else{
				
				//上传临时素材
				$media_id = up_temp_material($app['head_img']);
				$access_token = getAccessToken();
				//执行修改头像
				$url = 'https://api.weixin.qq.com/cgi-bin/account/modifyheadimage?access_token='.$access_token;
				$data = '{"head_img_media_id":"'.$media_id.'","x1":0,"y1":0,"x2":1,"y2":1}';
				$result = json_decode(http_request($url,$data),true);
				if($result['errcode']!=0){
					return $this->renderError('设置失败,错误代码：'.$result['errcode'].'错误说明：'.$result['errmsg']);
				}
				$app['head_img'] = '/uploads/'.$app['head_img']; 
				if ($wxapp->edit($app)){
					return $this->renderSuccess('设置成功', url('wxapp/setting'));
				}
				return $this->renderError('设置失败');
				
			}
        }
        return $this->fetch('sethead', compact('wxapp'));
    }
	
	
	/**
	* 查询昵称设置状态
	*/
	public function querynickname(){
		$audit_id='454738159';
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/api_wxa_querynickname?access_token='.$access_token;
		$data = '{"audit_id":"'.$audit_id.'"}';
		$result = http_request($url,$data);
		return $result;
	}
	
	/**
	* 获取附近小程序 - 服务类目
	*/
	public function nearby(){
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/get_merchant_category?access_token='.$access_token;
		$result = json_decode(curl($url),true);
		write_log($result,__DIR__);
		return $result;
	}
	
	/**
	* 获取小程序设置信息
	*/
	public function getInfor(){
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/account/getaccountbasicinfo?access_token='.$access_token;
		$result = json_decode(curl($url),true);
		return $result;
	}
	
	/**
	* 获取审核时可填写的类目信息
	*/
	public function getshowwxaitem()
	{
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/getshowwxaitem?access_token='.$access_token;
		return curl($url);
	}
	
	/**
     * 一键扫码授权
     */
    public function authorize()
    {
		$auth_code = empty ( $_GET ['auth_code'] ) ?"" : trim ( $_GET ['auth_code'] );	//获取授权码
		$config = ConfigModel::detail();
		if(!empty($auth_code)){
			//获取授权信息
			$result = getAuth($config['app_id'], $config['component_access_token'], $auth_code);
			$auth = $result['authorization_info'];//得到授权信息
				
			//获取授权应用的帐号基本信息
			$result = getAppInfo($config['app_id'], $config['component_access_token'], $auth['authorizer_appid']);
			$app = $result['authorizer_info'];//得到授权应用的帐号基本信息
			$wxapp = WxappModel::detail(); //获取商户数据
			$wxapp_id = $wxapp['wxapp_id'];
			$wxapp->edit([
				'app_name' => isset($app['nick_name'])?$app['nick_name']:'',	//昵称
				'head_img' => isset($app['head_img'])?$app['head_img']:'',		//头像
				'user_name' => $app['user_name'],					//原始ID
				'principal_name' => $app['principal_name'],			//主体名称
				'signature' => isset($app['signature'])?$app['signature']:'',	//账号介绍
				'api_domain' => $config['api_domain'],//服务器域名
				'app_id' => $auth['authorizer_appid'],				//授权方APPid
				'access_token' => $auth['authorizer_access_token'],	//令牌
				'expires_in' => time()+7000,						//令牌过期时间
				'authorizer_refresh_token' => $auth['authorizer_refresh_token'],	//刷新令牌
				'is_empower' => 1,	//是否授权				
			]);
			//清除缓存
			Cache::rm('wxapp_' . $wxapp_id);
			$this->redirect('wxapp/setting');
		}
		if(empty($config['app_id']) OR empty($config['component_access_token'])){
			$this->error('第三方参数配置错误', 'wxapp/setting');
            return false;
		}
		$url = authUrl($config['app_id'],$config['component_access_token'],2);//获取授权页面地址
		$this->redirect($url);
	}

}
